package com.lfz.search.config;

import org.springframework.amqp.core.AnonymousQueue;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;

import static com.lfz.search.config.Constant.JOB_ITEM_PUT_QUEUE_NAME;
import static com.lfz.search.config.Constant.JOB_ITEM_SEARCH_QUEUE_NAME;

/**
 * @author Daniel
 */
@Configuration
@EnableAsync
public class RabbitConfig {

    @Bean
    public Queue asyncRPCQueue() {
        return new Queue(JOB_ITEM_PUT_QUEUE_NAME);
    }

    @Bean
    public Queue asyncSearchRPCQueue() {
        return new Queue(JOB_ITEM_SEARCH_QUEUE_NAME);
    }

    @Bean
    public Queue repliesQueue() {
        return new AnonymousQueue();
    }

    @Bean
    @Primary
    public SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames(repliesQueue().getName());
        return container;
    }

    @Bean
    public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate template, SimpleMessageListenerContainer container) {
        return new AsyncRabbitTemplate(template, container);
    }

}
